<?php

namespace Gaolei\YiiRBAC\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;
use Gaolei\YiiRBAC\models\Adminer;
use Gaolei\YiiRBAC\models\Assignment;

/**
 * Class AllotController 权限分配
 * @package Gaolei\YiiRBAC\controllers
 */
class AllotController extends Controller
{

    public $userClassName;
    public $idField = 'id';
    public $usernameField = 'username';
    public $realnameField = 'realname';

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'assign' => ['post'],
                    'revoke' => ['post'],
                ],
            ],
        ];
    }

    protected $admin;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        if ($this->userClassName === null) {
            $this->userClassName = Yii::$app->getUser()->identityClass ?: Adminer::class;
        }
        $this->admin = \Yii::$app->user->identity;
    }

    protected function canOperate(int $id): bool
    {
        $user = Adminer::findOne($id);
        if (!$user) {
            Yii::$app->session->setFlash('error', "要操作的管理员不存在");
            return false;
        }
        if($this->admin->getId() !== 1){
            if ($user->id === $this->admin->getId()) {
                Yii::$app->session->setFlash('error', "管理员不能修改自己的账号");
                return false;
            }
            if ($user->id === 1) {
                Yii::$app->session->setFlash('error', "超级管理员不可修改");
                return false;
            }
            if ($this->admin->level < $user->level) {
                Yii::$app->session->setFlash('error', "你没有权限进行此操作");
                return false;
            }
        }
        return true;
    }

    /**
     * @param int $id
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionIndex(int $id)
    {
        if ($this->canOperate($id)) {
            $model = $this->findModel($id);
            return $this->render('view', [
                'model' => $model,
                'idField' => $this->idField,
                'usernameField' => $this->usernameField,
                'realnameField' => $this->realnameField,
            ]);
        }
        return $this->goBack();
    }

    /**
     * Assign items
     * @param string $id
     * @return array
     */
    public function actionAssign(string $id): array
    {
        if ($this->canOperate($id)) {
            $items = Yii::$app->getRequest()->post('items', []);
            $model = new Assignment($id);
            $success = $model->assign($items);
            Yii::$app->getResponse()->format = 'json';
            return array_merge($model->getItems(), ['success' => $success]);
        }
        return [];

    }

    /**
     * @param string $id
     * @return array
     */
    public function actionRevoke(string $id): array
    {
        if ($this->canOperate($id)) {
            $items = Yii::$app->getRequest()->post('items', []);
            $model = new Assignment($id);
            $success = $model->revoke($items);
            Yii::$app->getResponse()->format = 'json';
            return array_merge($model->getItems(), ['success' => $success]);
        }
        return [];
    }

    /**
     * @param int $id
     * @return Assignment
     * @throws NotFoundHttpException
     */
    protected function findModel(int $id): Assignment
    {
        $class = $this->userClassName;
        if (($user = $class::findIdentity($id)) !== null) {
            return new Assignment($id, $user);
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
